# -*- coding: utf-8 -*-

# @File  : csv.py
# @Author: Lomo
# @Site  : lomo.space
# @Date  : 2019-11-28
# @Desc  : CSV 文件操作

import os
import datetime
import csv

from settings import PROJECT_DIR


class CSV(object):
    CONFIG_DIR = '/outputs'

    def __init__(self):
        # print(os.path.dirname(os.path.abspath(__file__)))  # /Users/lomo/Mryt/qa/dsr/utils
        is_exist = os.path.exists(PROJECT_DIR + self.CONFIG_DIR)
        if not is_exist:
            os.mkdir(PROJECT_DIR + self.CONFIG_DIR)

    def create_csv(self, file_name=None):
        if file_name is None:
            file_name = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
        create_dir = PROJECT_DIR + self.CONFIG_DIR
        os.system('touch {0}/{1}.csv'.format(create_dir, file_name))
        return '{0}/{1}.csv'.format(create_dir, file_name)

    @staticmethod
    def write_csv(file_path, rows, headers=None):
        """
        追加模式写 csv
        :param file_path: 文件路径
        :param headers: csv header
        :param rows: [] or [[],[],[]] or [(),(),()]
        :return: None
        """
        if CSV.read_csv(file_path):
            has_header = CSV.read_csv(file_path)[0] == headers
        else:
            has_header = False
        with open(file_path, mode='a', encoding='utf-8') as f:
            f_csv = csv.writer(f)
            if headers is not None and has_header is False:
                f_csv.writerow(headers)

            if isinstance(rows, list):
                # 二维数组
                for obj in rows:
                    if isinstance(obj, (list, tuple)):
                        # TODO: list 做了一次转换有性能损耗, 待解决
                        f_csv.writerow(list(obj))
                    else:
                        f_csv.writerow(rows)
                        break

    @staticmethod
    def read_csv(file_path):
        """
        读取 csv 并返回 list
        :param file_path: 文件路径
        :return: list
        """
        with open(file_path, encoding='utf-8') as f:
            csv_r = csv.reader(f)
            rows = [row for row in csv_r]
        return rows


